package com.base.project.deeplinks

import android.app.Activity
import android.content.Intent
import com.base.project.Constants
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeoutOrNull

/**
 * Created by Orange on 2022/12/3 22:48.
 * 处理深度链接
 */
object DeepLinksHelper {

    private const val timeOut = 3000L //设定处理深度链接超时时间 返回null

    private val tasks = listOf(FirebaseTask(), FacebookTask(), GoogleTask())

    /**
     * 默认在io线程处理
     */
    suspend fun collectDeepLinks(
        activity: Activity,
        intent: Intent?,
        defaultDispatcher: CoroutineDispatcher = Dispatchers.IO
    ): LinkData? {
        return withContext(defaultDispatcher) {
            /**
             * 原方案是用select 发现是等待所有的 async 完成之后取最快的结果
             * 现在改成串行 有结果就返回 测试比并行要更快的获取到Firebase链接
             */
            var linkData = withTimeoutOrNull(timeOut) {
                tasks.forEach {
                    async { it.asyncGetUrl(activity, intent) }.await()?.let { link ->
                        return@withTimeoutOrNull link
                    }
                }
                null
            }
            // 解析一下参数 并返回
            linkData?.apply {
                uri?.apply {
                    rId = getQueryParameter("r_id") ?: ""
                    pageType = getQueryParameter("page_type")?.toInt() ?: 0
                    url = getQueryParameter("url") ?: ""
                    inviteType = getQueryParameter("invite_type") ?: ""

                    Constants.inviteId = rId
                }
            }
        }
    }
}